package com.kcyu.sfherp.config.MQTT;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttSample {

    static MqttClient client;

    public static void main(String[] args) throws MqttException {
        connect();
        sendMessage("/sfherp/newOrder", "123456");
    }

    public static void connect() throws MqttException {
        int qos = 2;
        String broker = "ssl://l76a0de8.ala.cn-hangzhou.emqxsl.cn:8883";
        String clientId = MqttClient.generateClientId();
        // 持久化
        MemoryPersistence persistence = new MemoryPersistence();
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // 设置认证信息
        connOpts.setUserName("kcyu1");
        connOpts.setPassword("4404050".toCharArray());

        client = new MqttClient(broker, clientId, persistence);
        // 设置回调
        client.setCallback(new SampleCallback());
        // 建立连接
        System.out.println("Connecting to broker: " + broker);
        client.connect(connOpts);
        System.out.println("Connected to broker: " + broker);
    }

    public static void sendMessage(String topic, String content) throws MqttException {
        MqttMessage message = new MqttMessage(content.getBytes());
        client.publish(topic, message);
    }

    public MqttClient getClient() {
        return this.client;
    }
}
